package com.zxy.supplier_system.server.service

import com.zxy.supplier_system.server.controller.MarketStatisticController
import com.zxy.supplier_system.server.controller.MarketStatisticController.MarketSoldEveryMonthStatisticResponse
import com.zxy.supplier_system.server.repository.MarketStatisticRepository
import org.springframework.stereotype.Service
import java.time.YearMonth

@Service
class MarketStatisticService(
    private val marketStatisticRepository: MarketStatisticRepository,
    private val systemServiceService: SystemServiceService,
) {
    fun statistic(
        marketId: Int,
        request: MarketStatisticController.MarketStatisticRequest
    ): MarketStatisticController.MarketStatisticResponse {
        val systemService = systemServiceService.getCurrentSystemService()
        val statistic = this.marketStatisticRepository.statisticAuditedMarketOrderByMarketStatisticRequest(
            marketId, request,
            systemService
        )
        return MarketStatisticController.MarketStatisticResponse(
            statistic.totalPrice,
            statistic.deliveryOrderCount,
            statistic.totalCost,
            this.marketStatisticRepository.statisticAuditedMarketSaleDocumentByMarketStatisticRequest(
                marketId, request,
                systemService
            )
        )
    }

    fun soldStatistic(id: Int, request: MarketStatisticController.MarketStatisticRequest):MarketSoldEveryMonthStatisticResponse {
        val systemService = systemServiceService.getCurrentSystemService()
        return MarketSoldEveryMonthStatisticResponse(
            this.marketStatisticRepository.statisticAuditMarketSaleDocumentByMarketGroupByYearMonth(id,request,systemService).map {
                MarketSoldEveryMonthStatisticResponse.YearMonthData(YearMonth.of(it.year,it.month),it.money)
            }
        )
    }
}